let state = {
    song: {  //当前所播放的歌曲对象
        name: "未播放音乐", //歌曲的名字
        songName: "", //暂时存储歌曲的名字，当歌曲可以播放时就将songName的值赋予name属性
        author: "未知", //歌手名
        musicUrl: "",//歌曲的地址
        // https://i.loli.net/2020/03/26/k1KaSpxN47qi9Xc.jpg  是默认的图片路径，
        // 因为在搜索页面获取的歌曲数据时没有图片的
        picUrl: "https://i.loli.net/2020/03/26/k1KaSpxN47qi9Xc.jpg",
        id: "",
        lyric: []//存储歌词的数组
    },
    list: [],//播放列表数组
    index: 0,//记录当前所播放的音乐在播放列表数组的索引值,
}

let mutations = {
    DECREMENT_MAIN_COUNTER(state) {
        state.main--
    },
    INCREMENT_MAIN_COUNTER(state) {
        state.main++
    },
    // 更改播放器的播放状态
    CHANGE_STATUS(state) {
        state.audioState = !state.audioState
    },
    // 更改播放模式
    CHANGE_MODEL(state, index) {
        state.model = index
    },
    //点击歌曲时触发的事件
    UPDATE_SONG(state, data) {
        state.song = data.music
        let music = data.music

        // 判断播放列表中是否已经存在该歌曲
        var result = state.list.findIndex(item => {
            return music.id === item.id
        })
        //不存在则添加到播放列表中
        if (result == -1) {
            var newsong = {
                name: music.songName,
                author: music.author,
                id: music.id,
                picUrl: music.picUrl
            }
            state.list.push(newsong);
            state.index = state.list.length - 1;
        } else {  //存在则只修改index的值
            state.index = result
        }

        //获取到audio标签
        var audio = document.getElementById("myaudio");
        if (data.autoplay) {  //判断传递过来的autoplay的值，因为在打开网页时歌曲是不自动播放的
            audio.setAttribute("autoplay", "autoplay");
            state.audioState = true
        } else {
            state.audioState = false
        }
        //将歌曲列表存储到本地
        window.localStorage.setItem("musicState", JSON.stringify({ list: state.list, index: state.index }), new Date().getDate + 20);
    },
    // 更新播放状态，歌曲是否可以播放  歌曲名字由  正在加载中--->歌曲真正的名称
    UPDATE_STATUS(state, newName) {
        state.song.name = newName
    },
    // 删除歌曲列表中的歌曲
    DELETE_SONG(state, index) {
        state.list.splice(index, 1);
        if (state.list == 0) {  //歌曲列表为空
            state.index = 0;
        } else if (index == state.index) {  //删除的歌曲是正在播放的歌曲
            if (index == state.list.length - 1) {  //并且是最后一首歌曲
                state.index = 0;
            } else {
                state.index = index;
            }
            var item = state.list[state.index]
            this.dispatch("getSong", { id: item.id, autoplay: true })
        } else if (index < state.index) { //删除的正在播放歌曲前面的歌曲，需要修改index,否则会出现数组坍塌的情况
            state.index--
        }
        window.localStorage.setItem("musicState", JSON.stringify({ list: state.list, index: state.index }), new Date().getDate + 20);
    },

    // 清空列表
    DELETE_ALL(state) {
        state.list = []
        state.index = 0
        window.localStorage.setItem("musicState", JSON.stringify({ list: state.list, index: state.index }), new Date().getDate + 20);
    },

    // 点击播放全部时触发的事件
    ADD_LIST(state, list) {
        state.index = state.list.length;
        // 遍历歌曲，查看歌单中的歌曲在歌曲列表中是否存在，如果存在则不添加，但是newlist数组中该项的值是undefined
        var newlist = list.map(item => {
            let res = state.list.findIndex(item2 => {
                return item.id == item2.id
            })
            if (res == -1) {
                return {
                    name: item.name,
                    author: item.ar[0].name,
                    id: item.id,
                    picUrl: item.al.picUrl
                }
            }
        })
        // 删除数组中的undefined项
        newlist = newlist.filter(Boolean)
        state.list.push(...newlist);
        var item = state.list[state.index]
        this.dispatch("getSong", { id: item.id, autoplay: true })
        window.localStorage.setItem("musicState", JSON.stringify({ list: state.list, index: state.index }), new Date().getDate + 20);
    },
    // 更新index
    UPDATE_INDEX(state, index) {
        if (state.index == index) return
        state.index = index
        var item = state.list[state.index]
        this.dispatch("getSong", { id: item.id, autoplay: true })
        window.localStorage.setItem("musicState", JSON.stringify({ list: state.list, index: state.index }), new Date().getDate + 20);
    },
    // 下一首
    NEXT(state) {

        //判断播放模式（是循坏播放或者是单曲循环时，index++）
        if (state.model == 0 || state.model == 1) {
            if (state.index == state.list.length - 1) {
                state.index = 0
            } else {
                state.index++
            }
        } else {
            //是随机播放则产生一个随机数
            state.index = Math.ceil(Math.random() * state.list.length)
        }

        var item = state.list[state.index]
        this.dispatch("getSong", { id: item.id, autoplay: true })
        window.localStorage.setItem("musicState", JSON.stringify({ list: state.list, index: state.index }), new Date().getDate + 20);
    },
    //上一首
    PREV(state) {
        if (state.model == 0 || state.model == 1) {
            if (state.index == 0) {
                state.index = state.list.length - 1
            } else {
                state.index--
            }
        } else {
            state.index = Math.ceil(Math.random() * state.list.length)
        }
        var item = state.list[state.index]
        this.dispatch("getSong", { id: item.id, autoplay: true })
        window.localStorage.setItem("musicState", JSON.stringify({ list: state.list, index: state.index }), new Date().getDate + 20);
    },
    // 初始化从本地读取缓存触发的事件
    PUSH_LIST(state, oldstate) {
        //当播放列表存在时才触发
        if (oldstate.list) {
            state.list = oldstate.list;
            state.index = oldstate.index;
            let item = state.list[state.index]
            this.dispatch("getSong", { id: item.id, autoplay: false })
        }
    },
}

let actions = {
    async getSong(context, data) {
        let result = await GetSongDetail({
            ids: data.id
        })
        let song = result.songs[0]
        let music = {
            id: data.id,
            name: "歌曲正在加载中...",
            songName: song.name,
            picUrl: song.al.picUrl,
            author: song.ar[0].name,
        }
        let res = await GetSongUrl({
            id: data.id
        })


        //判断是否可以获取到歌曲的播放地址
        if (!res.data[0].url) {
            Vue.prototype.$notify.error({
                title: "错误",
                message: `歌曲 ${music.songName} 是vip歌曲无法获取`
            });
            return;
        }

        // 获取歌词
        let lyric = await GetLyric({
            id: data.id
        })

        if (lyric.lrc) {
            lyric = lyric.lrc.lyric
        } else {
            lyric = "暂无歌词"
        }

        let newlyric = parseLyric(lyric)
        music.src = res.data[0].url
        music.lyric = newlyric

        let autoplay = data.autoplay
        this.commit("UPDATE_SONG", { music, autoplay })
    },
}

let getters = {
    // 获取audio的播放状态
    getState: state => {
        return state.audioState
    },
    // 获取播放模式
    getModel: state => {
        return state.model
    },
    // 获取歌曲名称
    getName: state => {
        return state.song.name
    },
    // 获取歌曲作者
    getAuthor: state => {
        return state.song.author
    },
    // 获取歌曲地址
    getMusicUrl: state => {
        return state.song.src
    },
    // 获取歌曲时长
    getDuration: state => {
        return state.duration
    },
    // 获取歌曲当前时间
    getCurrentTime: state => {
        return state.currentTime
    },
    // 获取歌词
    getLyrics: state => {
        return state.song.lyric
    },
    // 获取歌词的显示状态
    getShowLyrics: state => {
        return state.showLyrics
    },
    // 获取当前歌词的行号
    getLyricsIndex: state => {
        return state.lyricsIndex
    },
    // 获取歌曲图片
    getImgUrl: state => {
        return state.song.picUrl
    },
    // 获取歌曲在列表中的index值
    getIndex: state => {
        return state.index
    },
    // 获取播放列表
    getMusicList: state => {
        return state.list
    },
}

export default {
    state,
    mutations,
    actions,
    getters
}
